package com.hyc.DataStructure.PriorityQueue;

import java.util.Arrays;
import java.util.Comparator;
import java.util.PriorityQueue;

/**
 * @projectName: DataStructure
 * @package: com.hyc.DataStructure.PriorityQueue
 * @className: smallestK
 * @author: 冷环渊 doomwatcher
 * @description: TODO
 * @date: 2022/2/26 18:04
 * @version: 1.0
 */
public class smallestK {
    public static void main(String[] args) {
        int[] arr = {1, 3, 5, 7, 2, 4, 6, 8};
        System.out.println(Arrays.toString(smallestK(arr, 4)));
    }

    public static int[] smallestK(int[] arr, int k) {
        Arrays.sort(arr);
        int[] result = new int[k];
        for (int i = 0; i < k; i++) {
            result[i] = arr[i];
        }
        return result;
    }

    public static int[] smallestKByQueue(int[] arr, int k) {
        PriorityQueue<Integer> queue = new PriorityQueue<>();
        int[] result = new int[k];
        for (int i = 0; i < arr.length; i++) {
            queue.offer(arr[i]);
        }
        for (int j = 0; j < k; j++) {
            result[j] = queue.poll();
        }
        return result;
    }

    public static int[] smallestByHeap(int[] arr, int k) {
        PriorityQueue<Integer> queue = new PriorityQueue<>(new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return o1 - o2;
            }
        });
        int[] result = new int[k];
        for (int i = 0; i < arr.length; i++) {
            queue.offer(arr[i]);
        }
        for (int i = 0; i < arr.length - k; i++) {
            queue.poll();
        }
        for (int j = 0; j < k; j++) {
            result[j] = queue.poll();
        }
        return result;
    }
}
